package com.elephant.core.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: hai
 * @Date: 2019/1/3 14:50
 */
public class ReentrantLockTest implements Runnable{
    public static ReentrantLock lock = new ReentrantLock();
    public static int i = 0;
    public static int COUNT = 10000;

    @Override
    public void run() {
        for (int j = 0; j < COUNT; j++) {
            //lock.lock();
            try {
                if(lock.tryLock()){
                    i++;
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockTest test = new ReentrantLockTest();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.start();t2.start();
        // main线程会等待t1和t2都运行完再执行以后的流程
        t1.join(); t2.join();
        System.err.println(i);
    }
}